// 产品详情页面专用JavaScript

// 品牌配置管理（简化版，只用于获取logo）
class BrandConfig {
  constructor() {
    this.brands = {};
    this.loaded = false;
  }

  async loadConfig() {
    if (this.loaded) return this.brands;

    try {
      const response = await fetch("/static/config.json");
      const config = await response.json();
      this.brands = config.brands || {};
      this.loaded = true;
      return this.brands;
    } catch (error) {
      console.error("Error loading brand config:", error);
      return {};
    }
  }

  getBrand(brandName) {
    // 产品名转为小写
    brandName = brandName.toLowerCase();
    return this.brands[brandName] || null;
  }

  getBrandLogo(brandName) {
    const brand = this.getBrand(brandName);
    return brand ? brand.logo : null;
  }
}

// 产品详情管理
class ProductDetailManager {
  constructor() {
    this.product = null;
  }

  async fetchProductDetail(productId) {
    try {
      const token = this.getAuthToken();

      const headers = {
        "Content-Type": "application/json",
      };

      if (token) {
        headers["Authorization"] = `Bearer ${token}`;
      }

      const response = await fetch(`/api/product/${productId}`, { headers });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();

      if (result.code === 1) {
        this.product = result.data;
        return result.data;
      } else {
        throw new Error(result.message || "API returned error");
      }
    } catch (error) {
      console.error("Error fetching product detail:", error);
      return null;
    }
  }

  getAuthToken() {
    const cookies = document.cookie.split(";");
    for (let cookie of cookies) {
      const [name, value] = cookie.trim().split("=");
      if (name === "authorized-token") {
        try {
          const tokenData = JSON.parse(decodeURIComponent(value));
          return tokenData.access_token;
        } catch (e) {
          console.error("Error parsing auth token:", e);
          return null;
        }
      }
    }
    return null;
  }

  renderProductDetail(product, containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const hasPrice = product.price !== undefined;
    const priceDisplay = hasPrice
      ? `¥${product.price}/年`
      : "请联系客服获取报价";

    // 验证类型映射
    const validationTypeMap = {
      dv: "DV 域名验证",
      ov: "OV 组织验证",
      ev: "EV 扩展验证",
    };

    // 域名类型映射
    const getDomainTypes = (types) => {
      const typeMap = {
        wildcard: "通配符",
        standard: "单域名",
        ipv4: "IPV4",
      };
      return types.map((t) => typeMap[t] || t).join("/");
    };

    // 验证方法
    const getValidationMethods = (methods) => {
      const methodMap = {
        admin: "EMAIL",
        administrator: "EMAIL",
        postmaster: "EMAIL",
        hostmaster: "EMAIL",
        webmaster: "EMAIL",
      };

      methods = methods.map((m) => methodMap[m] || m.toUpperCase());
      // 去重
      methods = [...new Set(methods)];

      return methods.join("/");
    };

    // 获取有效期选项
    const getPeriods = (periods) => {
      if (periods && periods.length > 0) {
        // 大于12个月转换为年
        return periods
          .map((p) => (p >= 12 ? `${p / 12}年` : `${p}个月`))
          .join("/");
      }
      return "1年";
    };

    // 获取品牌logo
    const brandLogo = brandConfig.getBrandLogo(product.brand);
    const logoHTML = brandLogo
      ? `<img src="${brandLogo}" alt="${product.brand}" style="height: 80px;">`
      : `<svg width="120" height="80" viewBox="0 0 120 80" xmlns="http://www.w3.org/2000/svg">
            <rect width="120" height="80" rx="8" fill="${this.getRandomColor()}"/>
            <text x="60" y="48" text-anchor="middle" fill="white" font-size="16">${
              product.brand || "SSL"
            }</text>
        </svg>`;

    container.innerHTML = `
        <div class="product-detail">
            <div class="product-detail-header">
                <div class="product-brand-large">
                    ${logoHTML}
                </div>
                <h1>${product.name}</h1>
            </div>

            <div class="product-detail-content">
                <div class="product-specs">
                    <h3>产品规格</h3>
                    <div class="specs-grid">
                        <div class="spec-item">
                            <span class="spec-label">加密算法</span>
                            <span class="spec-value">${product.encryption_alg
                              .join("/")
                              .toUpperCase()}</span>
                        </div>
                        <div class="spec-item">
                            <span class="spec-label">验证类型</span>
                            <span class="spec-value">${
                              validationTypeMap[product.validation_type] || "DV"
                            }</span>
                        </div>
                        <div class="spec-item">
                            <span class="spec-label">域名类型</span>
                            <span class="spec-value">${getDomainTypes(
                              product.common_name_types
                            )}</span>
                        </div>

                        ${
                          product.alternative_name_types &&
                          product.alternative_name_types.length > 0
                            ? `<div class="spec-item">
                            <span class="spec-label">附加域名</span>
                            <span class="spec-value">${getDomainTypes(
                              product.alternative_name_types
                            )}</span>
                        </div>`
                            : ""
                        }
                        <div class="spec-item">
                            <span class="spec-label">保险金额</span>
                            <span class="spec-value">${
                              product.warranty_currency || "€"
                            }${product.warranty || "0"}</span>
                        </div>
                        <div class="spec-item">
                            <span class="spec-label">验证方式</span>
                            <span class="spec-value">${getValidationMethods(
                              product.validation_methods
                            )}</span>
                        </div>
                        <div class="spec-item">
                            <span class="spec-label">订单周期</span>
                            <span class="spec-value">${getPeriods(
                              product.periods
                            )}</span>
                        </div>
                        <div class="spec-item">
                            <span class="spec-label">重新签发</span>
                            <span class="spec-value">${
                              product.reissue ? "支持" : "不支持"
                            }</span>
                        </div>
                        <div class="spec-item">
                            <span class="spec-label">退款期限</span>
                            <span class="spec-value">${
                              product.refund_period || 30
                            }天</span>
                        </div>
                    </div>
                </div>

                ${
                  product.remark
                    ? `
                <div class="product-remark" style="margin: 30px 0; padding: 20px; background: var(--bg-light); border-radius: 8px;">
                    <h4 style="margin-bottom: 10px; color: var(--primary-blue);">产品说明</h4>
                    <p style="color: var(--text-dark);">${product.remark}</p>
                </div>
                `
                    : ""
                }

                <div class="product-actions">
                    <button class="btn btn-primary btn-large" onclick="location.href='/products'">← 返回产品列表</button>
                    <button class="btn btn-primary btn-large" onclick="purchaseProduct('${
                      product.id
                    }')">立即购买</button>
                    <button class="btn btn-outline btn-large" onclick="contactService()">联系客服</button>
                </div>
            </div>
        </div>
    `;
  }

  getRandomColor() {
    const colors = [
      "#3b82f6",
      "#ef4444",
      "#22c55e",
      "#f59e0b",
      "#8b5cf6",
      "#ec4899",
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  }
}

// 全局实例
const brandConfig = new BrandConfig();
const productDetailManager = new ProductDetailManager();

// 页面初始化
function initProductDetailPage() {
  const urlParams = new URLSearchParams(window.location.search);
  const productId = urlParams.get("id");

  if (!productId) {
    const container = document.getElementById("product-detail-container");
    if (container) {
      container.innerHTML = `
        <div class="error" style="text-align: center; padding: 60px 0;">
          <h2>产品ID未找到</h2>
          <p style="margin: 20px 0; color: var(--text-light);">请从产品列表页面选择一个产品查看详情</p>
          <a href="/products" class="btn btn-primary">返回产品列表</a>
        </div>
      `;
    }
    return;
  }

  // 先加载品牌配置，然后获取和渲染产品详情
  brandConfig.loadConfig().then(() => {
    productDetailManager.fetchProductDetail(productId).then((product) => {
      if (product) {
        productDetailManager.renderProductDetail(
          product,
          "product-detail-container"
        );
      } else {
        const container = document.getElementById("product-detail-container");
        if (container) {
          container.innerHTML = `
            <div class="error" style="text-align: center; padding: 60px 0;">
              <h2>产品信息加载失败</h2>
              <p style="margin: 20px 0; color: var(--text-light);">请稍后再试或联系客服</p>
              <div style="margin-top: 30px;">
                <a href="/products" class="btn btn-primary" style="margin-right: 15px;">返回产品列表</a>
                <button class="btn btn-outline" onclick="location.reload()">重新加载</button>
              </div>
            </div>
          `;
        }
      }
    });
  });
}

// 购买产品功能
function purchaseProduct(productId) {
  window.location.href = `/user/order?type=apply&product_id=${productId}`;
}

// 联系客服功能
function contactService() {
  // 跳转到联系页面
  window.location.href = "/contact";
}

// 公开函数
window.initProductDetailPage = initProductDetailPage;
window.purchaseProduct = purchaseProduct;
window.contactService = contactService;
